import { defineStore } from 'pinia'
import { getDictList } from '@/api/dict/index'
import { getUserInfo } from '@/api/user/index'
import { getFlattenDictData } from '@/utils/dictMeth'
import { setKey } from '@/utils/cookie'
import { getLanguage } from '@/i18n/index'

const baseData = defineStore('base', {
  state: () => ({
    flattenDictData: {}, // 扁平化的数据字典
    userInfo: {},
    language: getLanguage(),
    langOptions: [
      {
        value: 'zh-CN',
        label: '简体'
      },
      {
        value: 'en',
        label: 'English'
      },
      {
        value: 'de',
        label: 'Deutsch'
      },
      {
        value: 'fr',
        label: 'Français'
      },
      {
        value: 'ja',
        label: '日本語'
      }
    ],
    // 主题色 default-theme dark-theme
    themeName: 'white'
  }),
  getters: {
    getDictList() {
      return (catRoute, with_defunct = true) => {
        let dataList = this.flattenDictData[catRoute]?.children
        if (!dataList || !dataList.length) return []
        if (with_defunct) {
          dataList = (dataList || []).filter((item) => {
            return item.defunctInd === '0'
          })
        }
        return dataList
      }
    },
    dictDefaultVal() {
      return (catRoute) => {
        const dataList = this.flattenDictData[catRoute]?.children
        if (!dataList || !dataList.length) return ''
        const obj = dataList.find((item) => {
          return item.defaultInd === '1' && item.defunctInd === '0'
        })
        return obj ? obj.catDesc : ''
      }
    },
    getDictDesc() {
      return (catRoute) => {
        const catDesc = this.flattenDictData[catRoute]?.catDesc
        return catDesc || ''
      }
    }
  },
  actions: {
    updatedThemeName(data) {
      this.themeName = data
    },
    setFlattenDictData() {
      return getDictList().then((res) => {
        if (res.resp_code === 0 && res.datas) {
          const dictData = getFlattenDictData(res.datas)
          window.flattenDictData = dictData // 多语言需要用到
          this.flattenDictData = dictData
          return res.datas
        }
      })
    },
    getUserInfo() {
      return getUserInfo().then((res) => {
        if (res.resp_code === 0 && res.datas) {
          this.userInfo = res.datas
          setKey('userName', res.datas.firstName + res.datas.lastName)
          setKey('userId', res.datas.id)
          return res.datas
        }
      })
    },
    resetUserInfo() {
      this.userInfo = {}
    },
    setLanguage(data = getLanguage()) {
      this.language = data
      localStorage.setItem('systemLanguage', data)
    }
  }
})

export default baseData
